package com.rchat.pocmini.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.airtalkee.sdk.AirtalkeeAccount;
import com.airtalkee.sdk.entity.AirContact;
import com.airtalkee.sdk.entity.AirSession;
import com.aso.common.http.bean.BaseBean;
import com.aso.common.http.delegate.HttpCallbackImpl;
import com.aso.common.http.utils.HttpUtils;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.baidu.mapapi.utils.OpenClientUtil;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.R;
import com.rchat.pocmini.account.PocAccount;
import com.rchat.pocmini.activity.bean.ClistBean;
import com.rchat.pocmini.activity.fragment.groups.GroupsPresenterImpl;
import com.rchat.pocmini.activity.listener.MediaListener;
import com.rchat.pocmini.activity.view.HorizontalListView;
import com.rchat.pocmini.activity.view.location.CommonAdapter;
import com.rchat.pocmini.activity.view.location.CommonViewHolder;
import com.rchat.pocmini.activity.view.location.CustomDialog1;
import com.rchat.pocmini.activity.view.location.MyOrientationListener;
import com.rchat.pocmini.bean.LocationBean;
import com.rchat.pocmini.common.BaseActivity;
import com.rchat.pocmini.global.HttpCodeGlobal;
import com.rchat.pocmini.global.UrlsGlobal;
import com.rchat.pocmini.service.PocService;
import com.rchat.pocmini.session.PocAirtalkeeSessionManager;
import com.rchat.pocmini.util.HttpUtil;
import com.rchat.pocmini.util.Sound;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by ljd on 2017/3/10.
 *
 * @deprecated 此类已废弃，新类LocationMvpActivity
 */

public class LocationActivity extends BaseActivity implements View.OnClickListener, MediaListener {

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocClient;
    public MyLocationListener myListener;
    private boolean isFirstLoc = true; // 是否首次定位

    private CommonAdapter<AirContact> mLv_horizonAdapter;
    private List<AirContact> mMemberList = new ArrayList<AirContact>();
    private ConcurrentHashMap<String, Marker> mMarkers = new ConcurrentHashMap<String, Marker>();
    private ConcurrentHashMap<String, Marker> mMarkerPoss = new ConcurrentHashMap<String, Marker>();
    private Marker myMarker;

    private ImageView talkIv;

    private Dialog memberDetailDialog;
    private RelativeLayout memberDetailLayout;
    private CustomDialog1 naviDialog, noMapDialog;

    private TextView mTv_map_name;
    private View mInflate;
    private LatLng latlng;

    private MyOrientationListener myOrientationListener;
    private int mXDirection;

    private PocAccount account;
    private String groupId;
    private String groupName;
    private AirSession airSession;
    private PocAirtalkeeSessionManager sessionManager;

    /**
     * 最新一次的经纬度
     */
    private double mCurrentLantitude;
    private double mCurrentLongitude;
    /**
     * 当前的精度
     */
    private float mCurrentAccracy;

    private CoordinateConverter converter;

    private AirContact myAirContact = new AirContact();
    private AirContact airContact = new AirContact();

    private TextView memberName, memberId;

    @Override
    public void initView() {
        groupId = getIntent().getStringExtra(GroupsPresenterImpl.KEY_GROUPID);
        groupName = getIntent().getStringExtra("groupName");
        myListener = new MyLocationListener();

        airSession = PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().sessionCall(groupId);
        account = PocAccount.getPocAccountInstance(LocationActivity.this);

        sessionManager = PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance();
        PocService.getInstance().setMediaListener(this);
//        sessionManager.setOnMediaListener(this);
        LinearLayout ll_head = (LinearLayout) findViewById(R.id.ll_head);
        ll_head.getBackground().setAlpha(80);
        findViewById(R.id.iv_location_back).setOnClickListener(this);
        findViewById(R.id.ori_location).setOnClickListener(this);
        talkIv = (ImageView) findViewById(R.id.iv_location_talk);
        talkIv.setOnClickListener(this);
        talkIv.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    sessionManager.talkRelease(airSession);
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    sessionManager.talkRequest(airSession);
                }
                return true;
            }
        });

        myAirContact.setIpocId(PocAccount.getPocAccountInstance(LocationActivity.this).getUserId());
        myAirContact.setDisplayName(account.getUserName());
        mMemberList.add(myAirContact);
        HorizontalListView lv_horizon = (HorizontalListView) findViewById(R.id.lv_horizon);
        lv_horizon.setAdapter(mLv_horizonAdapter = new CommonAdapter<AirContact>(
                LocationActivity.this, mMemberList,
                R.layout.item_location_member) {

            @Override
            public void convert(CommonViewHolder holder, AirContact item,
                                int position) {
                holder.setText(R.id.textView1, item.getDisplayName());
            }
        });
        lv_horizon.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AirContact airContact = (AirContact) parent.getItemAtPosition(position);
                if (airContact.getIpocId().equals(PocAccount.getPocAccountInstance(LocationActivity.this).getUserId())) {
                    LatLng ll = new LatLng(mCurrentLantitude, mCurrentLongitude);
                    targetToLatLng(ll, false);
                } else {
                    if (mMarkers.containsKey(airContact.getIpocId())) {
                        LatLng ll = mMarkers.get(airContact.getIpocId()).getPosition();
                        targetToLatLng(ll, false);
                    }
                }
            }
        });

        mInflate = getLayoutInflater().inflate(R.layout.map_head_view, null);
        mTv_map_name = (TextView) mInflate.findViewById(R.id.tv_map_name);

        mMapView = (MapView) findViewById(R.id.bmapView);
        mMapView.showZoomControls(false);
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        initOrientationListener();
        myOrientationListener.start();
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker arg0) {
                showMemberDetailDiaolog(arg0);
                return false;
            }
        });
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(10000);
        mLocClient.setLocOption(option);
        mLocClient.start();
//        converter = new CoordinateConverter();

        resultHandler.sendEmptyMessageDelayed(2,1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        resultHandler.removeMessages(1);
        resultHandler.removeMessages(2);
        mBaiduMap.clear();
        PocService.getInstance().unregisterMediaListener(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.location_activity_layout;
    }

    private void initOrientationListener() {
        myOrientationListener = new MyOrientationListener(LocationActivity.this);
        myOrientationListener
                .setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {

                    @Override
                    public void onOrientationChanged(float x) {
                        if (mMapView == null) {
                            return;
                        }
                        mXDirection = (int) x;
                        // 构造定位数据
                        LatLng myLatLng = new LatLng(mCurrentLantitude, mCurrentLongitude);
                        MyLocationData locData = new MyLocationData.Builder()
                                .accuracy(mCurrentAccracy)
                                // 此处设置开发者获取到的方向信息，顺时针0-360
                                .direction(mXDirection)
                                .latitude(mCurrentLantitude)
                                .longitude(mCurrentLongitude).build();
                        // 设置定位数据
                        mBaiduMap.setMyLocationData(locData);
                        // 设置自定义图标
                        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                                .fromResource(R.drawable.icon_map_diracton_self);
                        MyLocationConfiguration configuration = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker);
                        mBaiduMap.setMyLocationConfigeration(configuration);

                        if (myMarker == null) {
                            mTv_map_name.setText(account.getUserName());
                            BitmapDescriptor bd = BitmapDescriptorFactory.fromView(mInflate);
                            MarkerOptions ooA = new MarkerOptions().position(myLatLng).icon(bd);
                            Bundle b = new Bundle();
                            b.putString("id", PocAccount.getPocAccountInstance(LocationActivity.this).getUserId());
                            ooA.extraInfo(b);
                            myMarker = (Marker) mBaiduMap.addOverlay(ooA);
                        } else {
                            myMarker.setPosition(myLatLng);
                        }
                    }
                });
    }


    private void showMemberDetailDiaolog(final Marker marker) {
        if (marker.getExtraInfo() == null) {
            return;
        }

        if (memberDetailDialog == null) {
            LayoutInflater inflaterDl = LayoutInflater.from(this);
            memberDetailLayout = (RelativeLayout) inflaterDl.inflate(R.layout.dialog_member_detail, null);
            memberName = (TextView) memberDetailLayout.findViewById(R.id.tv_displayName);
            memberId = (TextView) memberDetailLayout.findViewById(R.id.tv_id);

            //对话框
            memberDetailDialog = new AlertDialog.Builder(LocationActivity.this).create();
            memberDetailDialog.setCanceledOnTouchOutside(true);

        }
        String id = marker.getExtraInfo().getString("id");

        Button talk_btn_navi = (Button) memberDetailLayout.findViewById(R.id.talk_btn_navi);
        if (id.equals(PocAccount.getUserId())) {
            memberName.setText(myAirContact.getDisplayName());
            if (PocAccount.isUserNameChanged()) {
                memberId.setText(PocAccount.getNewUserName());
            } else {
                memberId.setText(PocAccount.getUserName());
            }

            talk_btn_navi.setVisibility(View.INVISIBLE);
        } else {
            for (AirContact airContact : mMemberList) {
                if (airContact.getIpocId().equals(id)) {
                    memberName.setText(airContact.getDisplayName());
                    memberId.setText(airContact.getIpocId());
                    talk_btn_navi.setVisibility(View.VISIBLE);
                    break;
                }
            }
        }
        talk_btn_navi.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                memberDetailDialog.dismiss();
                showNaviDiaolog(marker);
            }
        });

        memberDetailDialog.show();
        memberDetailDialog.getWindow().setContentView(memberDetailLayout);
        Window dialogWindow = memberDetailDialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 0.75); // 宽度设置为屏幕的0.85
        p.height = (int) (d.getHeight() * 0.60);
        p.dimAmount = 0.2f;      //设置黑暗度
        dialogWindow.setAttributes(p);
    }

    //震动
//    private void callSystemVibrator() {
//        Vibrator vibrator;
//        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
//        vibrator.vibrate(new long[]{0, 150}, -1);
//    }

    private void showNaviDiaolog(final Marker endMarker) {
        naviDialog = new CustomDialog1(this, "使用百度地图进行导航？",
                "确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                naviDialog.dismiss();
                startNavi(endMarker);
            }
        }, new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                naviDialog.dismiss();
            }
        });

        naviDialog.show();
    }

    private void startNavi(Marker endMarker) {
        try {
            Intent i1 = new Intent();
            // 驾车路线规划
            Marker startMarker = myMarker;
            StringBuilder startSB = new StringBuilder(startMarker.getPosition().latitude + "");
            startSB.append(",");
            startSB.append(startMarker.getPosition().longitude + "");

            StringBuilder endSB = new StringBuilder(endMarker.getPosition().latitude + "");
            endSB.append(",");
            endSB.append(endMarker.getPosition().longitude + "");

            i1.setData(Uri.parse("baidumap://map/direction?origin=" + startSB.toString() + "&destination=" + endSB.toString() + "&mode=driving"));
            startActivity(i1);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            showNoMapDiaolog();
        }
    }

    private void showNoMapDiaolog() {
        if (noMapDialog == null) {
            noMapDialog = new CustomDialog1(this, "您尚未安装百度地图app或app版本过低，无法导航。",
                    "下载", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    noMapDialog.dismiss();
                    OpenClientUtil.getLatestBaiduMapApp(LocationActivity.this);
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    noMapDialog.dismiss();
                }
            });
        }

        noMapDialog.show();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            mCurrentLantitude = location.getLatitude();
            mCurrentLongitude = location.getLongitude();
            mCurrentAccracy = location.getRadius();
            LatLng myLatLng = new LatLng(location.getLatitude(), location.getLongitude());
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mXDirection)
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            // 设置定位数据
            mBaiduMap.setMyLocationData(locData);
            // 设置自定义图标
            BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                    .fromResource(R.drawable.icon_map_diracton_self);
            MyLocationConfiguration configuration = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker);
            mBaiduMap.setMyLocationConfigeration(configuration);

            if (myMarker == null) {
                mTv_map_name.setText(account.getUserName());
                BitmapDescriptor bd = BitmapDescriptorFactory.fromView(mInflate);
                MarkerOptions ooA = new MarkerOptions().position(myLatLng).icon(bd);
                myMarker = (Marker) mBaiduMap.addOverlay(ooA);
            } else {
                myMarker.setPosition(myLatLng);
            }

            // 第一次定位时，将地图位置移动到当前位置
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                targetToLatLng(ll, true);
            }

//            //获取频道成员其它位置信息
//            String queryOtherUserLocation = applyOtherUserLocationJson(groupId);
//            startLocationAboutThread(queryOtherUserLocation, HttpUtil.QUERY_LOCATION_LIST);

            float speed = 0.0f;
            double altitude = 0.0d;
//            //上报自己的定位信息
//            String reportLocationJson = uploadLocationJson(PocAccount.getUserId(), groupId, mCurrentLantitude, mCurrentLongitude, mXDirection);
//            startLocationAboutThread(reportLocationJson, HttpUtil.REPORT_LOCATION_URL);


            //GPS上报
//            if(PocSettingPreferences.getInstance(LocationActivity.this).getPocGpsReportState()){
//                AirtalkeeReport.getInstance().ReportLocation(getReportLocType(location.getLocType()), mCurrentLantitude, mCurrentLongitude,
//                        altitude, mXDirection, speed);
//            }

        }

        public void onReceivePoi(BDLocation poiLocation) {

        }
    }

    /**
     * 位置信息上报
     *
     * @param id
     * @param groupId
     * @param longitude
     * @param latitude
     * @param direction
     * @return
     */
    private String uploadLocationJson(String id, String groupId, double latitude, double longitude, int direction) {
        StringBuilder sb = new StringBuilder();
        sb
                .append("uid").append("=").append(id).append("&")
                .append("cid").append("=").append(groupId).append("&")
                .append("username").append("=").append(PocAccount.getUserName()).append("&")
                .append("longitude").append("=").append(longitude).append("&")
                .append("latitude").append("=").append(latitude).append("&")
                .append("direction").append("=").append(direction);
        return sb.toString();
    }

    /**
     * 获取其他用户的位置
     *
     * @param groupId
     * @return
     */
    private String applyOtherUserLocationJson(String groupId) {
        StringBuilder sb = new StringBuilder();
        sb.append("cid").append("=").append(groupId);
        return sb.toString();
    }

    /**
     * 执行位置相关的线程
     *
     * @param requestJson 登录请求json
     */
    private void startLocationAboutThread(final String requestJson, final String url) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                String backJson = httpConnect111(url, requestJson, HttpUtil.HTTP_POST);

                if (url.equals(UrlsGlobal.QUERY_LOCATION_LIST)) {
                    Message message = new Message();
                    message.what = 1;
                    message.obj = backJson;
                    resultHandler.sendMessage(message);
                }else {
//                    Log.e("requestJson",requestJson);
//                    Log.e("url",url);
//                    Log.e("backJson",backJson);
                }
            }
        };
        thread.start();
    }

    private Handler resultHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    final String backJson = (String) msg.obj;
                    if (backJson == null) {
                        return;
                    }
                    List<ClistBean> list = new ArrayList<>();
                    try {
                        JSONObject json = new JSONObject(backJson);
                        if (json.getString("code").equals("200")) {
                            JSONObject data = json.getJSONObject("data");
                            JSONArray clist = data.getJSONArray("clist");

                            for (int i = 0; i < clist.length(); i++) {
                                JSONObject loc = clist.getJSONObject(i);
                                ClistBean bean = new ClistBean();
                                bean.setId(loc.getString("id"));
                                bean.setUid(loc.getString("uid"));
                                bean.setCid(loc.getString("cid"));
                                bean.setLongitude(loc.getString("longitude"));
                                bean.setLatitude(loc.getString("latitude"));
                                bean.setDirection(loc.getString("direction"));
                                bean.setUptime(loc.getString("uptime"));

                                bean.setUsername(loc.getString("username"));
                                list.add(bean);
                            }
                            updateOverlay(list);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:
                    //获取频道成员其它位置信息
                    JSONObject root = new JSONObject();
                    try {
                        root.put("code", HttpCodeGlobal.REQ_CODE_1225);
                        JSONObject data = new JSONObject();
                        data.put("userName", AirtalkeeAccount.getInstance().getUserId());
                        data.put("groupId", groupId);
                        root.put("data", data);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //查询其他人的位置信息
                    HttpUtils.postAsyn(UrlsGlobal.getUrl(UrlsGlobal.LOCATION_REPORT),root.toString(), new HttpCallbackImpl<LocationBean>() {
                        @Override
                        public void onStart() {

                        }

                        @Override
                        public void onSuccess(LocationBean bean) {

                            ALog.d("desc = %s", bean.getDesc());
//                            Log.e("onSuccess",bean.getDesc());

                            List<ClistBean> list = new ArrayList<>();
                            for (LocationBean.DataBean.ClistBean b :bean.getData().getClist()) {
                                if(b.getUserName().equals(AirtalkeeAccount.getInstance().getUserId())){
                                    continue;
                                }
                                ClistBean bean1 = new ClistBean();
//                                bean1.setId(b.getString("id"));
//                                Log.e("bean",b.getDisplayName());
//                                Log.e("bean",b.getLatitude());
//                                Log.e("bean",b.getLongitude());
                                bean1.setUid(b.getDisplayName());
                                bean1.setCid(b.getDirection());

                                // 将GPS设备采集的原始GPS坐标转换成百度坐标    
//                                converter.from(CoordinateConverter.CoordType.GPS);
//                                // sourceLatLng待转换坐标
//
//                                converter.coord(new LatLng(Double.parseDouble(b.getLatitude()),Double.parseDouble(b.getLongitude())));
//                                LatLng desLatLng = converter.convert();

                                bean1.setLongitude(b.getLongitude() + "");
                                bean1.setLatitude(b.getLatitude() + "");
                                bean1.setDirection(b.getDirection());
                                bean1.setUptime(b.getDisplayName());
                                bean1.setUsername(b.getDisplayName());
                                list.add(bean1);
                            }
                            updateOverlay(list);

                        }

                        @Override
                        public void onFailureResult(BaseBean bean) {
                            List<ClistBean> list = new ArrayList<>();
                            updateOverlay(list);
                            ALog.d("code = %s,message = %s", bean.getCode(), bean.getDesc());
                        }

                        @Override
                        public void onFinish() {

                        }

                    });

//                    String queryOtherUserLocation = applyOtherUserLocationJson(groupId);
//                    startLocationAboutThread(queryOtherUserLocation, UrlsGlobal.QUERY_LOCATION_LIST);
                    resultHandler.sendEmptyMessageDelayed(2,10000);
            }
        }
    };



    private void updateOverlay(List<ClistBean> list) {
        if (mMapView == null) {
            return;
        }

//		if (json.getClist().isEmpty() && mMapView != null) {
//			mBaiduMap.clear();
//			Iterator iter = mMarkers.entrySet().iterator();
//			while (iter.hasNext()) {
//			    Map.Entry entry = (Map.Entry) iter.next();
//			    Marker val = (Marker) entry.getValue();
//			    val = null;
//			}
//		}

        Set<String> newKeys = new HashSet<String>();
        Set<String> oldInKeys = mMarkers.keySet();
        mMemberList.clear();
        mMemberList.add(myAirContact);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getUid().equals(PocAccount.getPocAccountInstance(LocationActivity.this).getUserId())) {
                continue;
            }
            newKeys.add(list.get(i).getUid());

            airContact = new AirContact();
            airContact.setIpocId(list.get(i).getUid());
            airContact.setDisplayName(list.get(i).getUsername());
            latlng = new LatLng(Double.parseDouble(list.get(i)
                    .getLatitude()), Double.parseDouble(list.get(i)
                    .getLongitude()));
            mMemberList.add(airContact);
        }
        mLv_horizonAdapter.notifyDataSetChanged();

        for (String key : oldInKeys) {
            if (newKeys.contains(key)) {
                //替换
            } else {
                if (mMapView != null) {
                    Marker val = mMarkers.get(key);
                    val.remove();
                    val = null;
                    mMarkers.remove(key);

                    Marker valPos = mMarkerPoss.get(key);
                    valPos.remove();
                    valPos = null;
                    mMarkerPoss.remove(key);
                }
            }
        }


        for (int i = 0; i < list.size(); i++) {
            ClistBean clist = list.get(i);
            if (mMapView != null) {
                latlng = new LatLng(Double.parseDouble(clist
                        .getLatitude()), Double.parseDouble(clist
                        .getLongitude()));
                if (mMarkers.containsKey(clist.getUid())) {
                    Marker mk = mMarkers.get(clist.getUid());
                    mk.setPosition(latlng);

                    Marker mkPos = mMarkerPoss.get(clist.getUsername());
                    if (mkPos != null) {
                        mkPos.setPosition(latlng);
                        mkPos.setRotate(Float.parseFloat(clist.getDirection()));
                        mkPos.setAnchor(0.5f, 0.5f);
                    }
                } else {
                    if (clist.getUid().equals(PocAccount.getPocAccountInstance(LocationActivity.this).getUserId())) {
                        continue;
                    }

                    BitmapDescriptor bdPos = BitmapDescriptorFactory.fromResource(R.drawable.icon_map_diracton_his);
                    MarkerOptions ooPos = new MarkerOptions().position(latlng).icon(bdPos)
                            .anchor(0.5f, 0.5f).rotate(Float.parseFloat(clist.getDirection()));
                    Bundle b = new Bundle();
                    b.putString("id", clist.getUid());
                    ooPos.extraInfo(b);
                    Marker mkPos = (Marker) (mBaiduMap.addOverlay(ooPos));
                    mMarkerPoss.put(clist.getUid(), mkPos);

                    mTv_map_name.setText(clist.getUsername());
                    BitmapDescriptor bd = BitmapDescriptorFactory.fromView(mInflate);
                    MarkerOptions ooA = new MarkerOptions().position(latlng).icon(bd);
                    ooA.extraInfo(b);
                    Marker mk = (Marker) (mBaiduMap.addOverlay(ooA));
                    mMarkers.put(clist.getUid(), mk);
                }
            }
        }
    }

    public static String httpConnect111(String urlStr, String requestJson, String method) {
        //建立连接
        StringBuffer buffer;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(method);
            conn.setConnectTimeout(10000);//十秒超时时间
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.connect();
//        Log.e("response code",conn.getResponseCode() + "");

            if (null != requestJson) {
                OutputStream outputStream = conn.getOutputStream();
                //注意编码格式
                outputStream.write(requestJson.getBytes("UTF-8"));
                outputStream.flush();
                outputStream.close();
            }
            inputStream = conn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            //释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            //释放资源
            try {
                if (null != bufferedReader) {
                    bufferedReader.close();
                }
                if (null != inputStreamReader) {
                    inputStreamReader.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (null != conn) {
                conn.disconnect();
            }
        }
        Log.e("LocationActivity",buffer.toString());
        return buffer.toString();
    }


    private void targetToLatLng(LatLng ll, boolean isNeedZoom) {
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(ll);
        if (isNeedZoom) {
            builder.zoom(18.0f);
        }
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory
                .newMapStatus(builder.build()));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_location_back:
                finish();
                break;
            case R.id.ori_location:
                LatLng ll = new LatLng(mCurrentLantitude, mCurrentLongitude);
                targetToLatLng(ll, false);
                break;
            default:
                break;
        }
    }

    @Override
    public void onMediaStateTalkPreparing(AirSession airSession) {
//        callSystemVibrator();
    }

    @Override
    public void onMediaStateTalk(AirSession airSession) {
        talkIv.setImageResource(R.drawable.ic_location_talk_pressed);
    }

    @Override
    public void onMediaStateTalkEnd(AirSession airSession, int i) {
        Sound.playSound(Sound.PLAYER_MEDIA_ME_OFF, this);
        talkIv.setImageResource(R.drawable.ic_location_talk);
    }

    @Override
    public void onMediaStateListen(AirSession airSession, AirContact airContact) {

    }

    @Override
    public void onMediaStateListenEnd(AirSession airSession) {

    }

    @Override
    public void onMediaStateListenVoice(AirSession airSession) {

    }

    @Override
    public void onMediaQueue(AirSession airSession, ArrayList<AirContact> arrayList) {

    }

    @Override
    public void onMediaQueueIn(AirSession airSession) {

    }

    @Override
    public void onMediaQueueOut(AirSession airSession) {

    }

    @Override
    public void onResume() {
        super.onResume();
        //友盟自定义统计开始
        MobclickAgent.onPageStart("LocationActivity");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //友盟自定义统计结束
        MobclickAgent.onPageEnd("LocationActivity");
        MobclickAgent.onPause(this);
    }
}
